//
//  CodeRankViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/8.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "CodeRankViewController.h"
#import "CodeRankTableViewCell.h"
#import "WebDetailInfoViewController.h"
#import "VIPWebViewController.h"
static NSString * cellIndentifier = @"CodeRankTableViewCell";
@interface CodeRankViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIImageView *personHead;
@property (strong, nonatomic) IBOutlet UIImageView *personVIP;
@property (strong, nonatomic) IBOutlet UILabel *personRank;
@property (strong, nonatomic) IBOutlet UILabel *personCode;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIScrollView *scroview;



@property(nonatomic,strong)NSMutableArray * rankArray;

@end

@implementation CodeRankViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _rankArray = [NSMutableArray array];
    _personHead.layer.masksToBounds = YES;
    _personHead.layer.cornerRadius = 35*VerticalRatio();

    [self initViewLayout];
    [self addRefreshing];
    [self getPersonalRank];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    self.view.backgroundColor = kGetColor(255, 217, 102);
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    _scroview.contentSize = flexibleSize(CGSizeMake(0, 505), NO);
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.scrollEnabled = YES;

    
   
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma mark == 奖励计划
- (IBAction)awardPlan:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"VIPServiceStoryboard" bundle:nil];
    VIPWebViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"VIPWeb"];
    page.url = SX_memberScorePrize;
    page.titleStr = @"积分奖励计划";
    [self.navigationController  pushViewController:page animated:YES];

}
#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getMyRank];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.rankArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getMyRank];
        });
    }
    
}


#pragma mark === 获取排行榜
- (void)getMyRank{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMypintdesc withHttpType:@"POST" withTag:SX_SX_queryMypintdesc];
    
    
}


#pragma mark === 获取个人排行榜
- (void)getPersonalRank{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryPersonCount withHttpType:@"POST" withTag:SX_SX_queryPersonCount];
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60*VerticalRatio();
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _rankArray.count-3;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CodeRankTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell= [[CodeRankTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
        NSString * image = _rankArray[indexPath.row+3][@"resImg"];
        cell.personHead.layer.masksToBounds = YES;
        cell.personHead.layer.cornerRadius = 20*VerticalRatio();
        if (image.length>0) {
            [cell.personHead sd_setImageWithURL:[NSURL URLWithString:image]];
        }
        
        cell.rankNumber.text = [NSString stringWithFormat:@"%ld",indexPath.row+4];
        cell.personName.text = [NSString stringWithFormat:@"%@",_rankArray[indexPath.row+3][@"museName"]];
        CGSize size = [cell.personName.text sizeWithFont:[UIFont systemFontOfSize:16*VerticalTexeRatio()] maxSize:flexibleSize(CGSizeMake(105, 19), NO)];
        cell.personLevel.frame = flexibleFrame(CGRectMake(97+size.width, 12, 19, 16), YES);
    NSString * rankimage = _rankArray[indexPath.row+3][@"rankImg"];
    if (rankimage.length>0) {
        [cell.personLevel sd_setImageWithURL:[NSURL URLWithString:rankimage]];
    }
        [cell.personCode setTitle:[NSString stringWithFormat:@"%@分",_rankArray[indexPath.row+3][@"ranking"]] forState:UIControlStateNormal] ;
        //    NSLog(@"%@", _rankArray[indexPath.row][@"mmelName"]);
    
   
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    //    ShopViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Shop"];
    //    [self.navigationController   pushViewController:page animated:YES];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag == SX_SX_queryMypintdesc){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
//                _totle = [database[@"result"][@"totalResults"] integerValue];
//                _totle = [database[@"result"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.rankArray removeAllObjects];
                }
//                NSArray *arr = database[@"result"][@"pageRecord"];
                NSArray *arr = database[@"result"];
                for (id entity in arr) {
                    [self.rankArray addObject:entity];
                }
                
                for (int i=0; i<3; i++) {
                    UIImageView * headImage = [self.view viewWithTag:(i+1)*1000];
                    NSString * image = [Common stringFromData:_rankArray[i][@"resImg"]];
                    headImage.layer.masksToBounds = YES;
                    headImage.layer.cornerRadius = 27.5*VerticalRatio();
                    if (i==0) {
                        headImage.layer.cornerRadius = 32.5*VerticalRatio();
                    }
                    if (image.length>0) {
                        [headImage sd_setImageWithURL:[NSURL URLWithString:image]];
                    }
                    
                    UILabel * name =[self.view viewWithTag:(i+1)*1000+1];
                    name.text = [Common stringFromData:_rankArray[i][@"museName"]];
                    
                    UIImageView * levelImage = [self.view viewWithTag:(i+1)*1000+2];
                    CGSize size = [name.text sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()] maxSize:flexibleSize(CGSizeMake(70, 21), NO)];
                    levelImage.frame = flexibleFrame(CGRectMake(CGRectGetMidX(name.frame)/VerticalRatio()+size.width/2, CGRectGetMinY(name.frame)/VerticalRatio()+2, 19, 16), YES);
                    NSString * rankimage = _rankArray[i][@"rankImg"];
                    if (rankimage.length>0) {
                        [levelImage sd_setImageWithURL:[NSURL URLWithString:rankimage]];
                    }
                    
                    UIButton * codeButton = [self.view viewWithTag:(i+1)*1000+3];
                     [codeButton setTitle:[NSString stringWithFormat:@"%@分",_rankArray[i][@"ranking"]] forState:UIControlStateNormal] ;
                }
                
                
                
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
            

            
        }
        
    }if (tag == SX_SX_queryPersonCount){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
        
            NSString * image = database[@"result"][0][@"resImg"];
            if (image.length>0) {
                [_personHead sd_setImageWithURL:[NSURL URLWithString:image]];
            }else{
               _personHead.image =[UIImage imageNamed:@"touxiang.png"];
            }
            NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",database[@"result"][0][@"rankingCount"]]];
//            [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000] range:NSMakeRange(5, [NSString stringWithFormat:@"%@",database[@"result"][0][@"rankingCount"]].length)];
            _personRank.attributedText = str;
            
            
            _personCode.text = [NSString stringWithFormat:@"%@",database[@"result"][0][@"ranking"]];

        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
